#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    vector<vector<int>> dir = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} };
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        const int DEL = INT_MIN;
        int i = 0, j = -1;
        int turn = 0;
        int n = matrix.size(), m = matrix[0].size();
        vector<int> res;
        while (res.size() < (n * m))
        {
            int a = i + dir[turn][0];
            int b = j + dir[turn][1];
            if (a >= n || a < 0 || b >= m || b < 0 || matrix[a][b] == DEL)
                turn = (turn + 1) % 4;
            i += dir[turn][0];
            j += dir[turn][1];
            res.push_back(matrix[i][j]);
            matrix[i][j] = DEL;
        }
        return res;
    }
};